package com.future.admin.diboot;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diboot.core.binding.Binder;
import com.diboot.core.binding.QueryBuilder;
import com.diboot.core.binding.RelationsBinder;
import com.diboot.core.binding.query.dynamic.ExtQueryWrapper;
import com.diboot.core.exception.BusinessException;
import com.diboot.core.vo.Pagination;

import java.util.List;

public class JoinUtil extends Binder {

    /**
     * 单表集合转关联查询
     *
     * @param entityList
     * @param voClass
     * @param <E>
     * @param <VO>
     * @return
     */
    public static <E, VO> List<VO> list(List<E> entityList, Class<VO> voClass) {
        return RelationsBinder.convertAndBind(entityList, voClass);
    }

    /**
     * 单表实体查询转关联查询
     *
     * @param entity
     * @param voClass
     * @param <E>
     * @param <VO>
     * @return
     */
    public static <E, VO> VO entity(E entity, Class<VO> voClass) {
        return RelationsBinder.convertAndBind(entity, voClass);
    }

    /**
     * 单表分页查询转关联查询
     *
     * @param page
     * @param voClass
     * @param <VO>
     * @return
     */
    public static <VO> Page page(Page page, Class<VO> voClass) {
        List records = page.getRecords();
        List list = RelationsBinder.convertAndBind(records, voClass);
        page.setRecords(list);
        return page;
    }

    /**
     * 多表分页
     *
     * @param page
     * @param entity
     * @param voClass
     * @param <E>
     * @param <VO>
     * @return
     */
    public static <E, VO> Page page(Page page, E entity, Class<VO> voClass) {
        if (page == null) {
            page = new Page();
            page.setCurrent(1);
            page.setSize(10);
        }
        ExtQueryWrapper extQueryWrapper = QueryBuilder.toDynamicJoinQueryWrapper(entity);
        Pagination pagination = new Pagination();
        pagination.setPageIndex((int) page.getCurrent());
        pagination.setPageSize((int) page.getSize());
        try {
            List<E> list = extQueryWrapper.queryList(voClass, pagination);
            page.setRecords(JoinUtil.list(list, voClass));
        } catch (BusinessException e) {

        }
        page.setTotal(pagination.getTotalCount());
        return page;
    }

}
